class AjaxDemo {
    constructor() {
        this.baseUrl = 'server/api.php';
        this.page = 1;
        this.initEventListeners();
    }

    initEventListeners() {
        document.getElementById('userForm').addEventListener('submit', (ev) => {
            ev.preventDefault(); // 阻止表单的默认提交行为，防止页面刷新
            this.addUser();
        });

        document.getElementById('loadMore').addEventListener('click', () => {
            this.loadUsers();
        });

        document.getElementById('uploadForm').addEventListener('submit', (ev) => {
            ev.preventDefault();
            this.uploadFile();
        });

        this.loadUsers();
    }

    loadUsers() {
        fetch(`${this.baseUrl}?action=getUsers&page=${this.page}`
            // , {
            //     credentials: 'include' // 允许跨域请求时携带 cookie
            // }
        ).then(response => {
            if (!response.ok) throw new Error('Network response was not ok' + response.statusText); // 抛出错误，以便catch处理
            return response.json()
        }).then(data => {
            if (data.success) {
                this.displayUsers(data.data);
                this.page++;
            } else {
                alert(`加载用户失败: ${data.data.message}`);
            }
        }).catch(error => {
            alert(`加载用户失败，请重试: ${error}`);
        });

        // // 创建 Request 对象来定制请求，fetch 会返回一个 Response 对象(可用它来获取不同类型的响应体: blob、text、json 等)
        // const request = new Request('flowers.jpg');
        // fetch(request).then(response => response.blob()).then(imageBlob => {
        //     img.src = URL.createObjectURL(imageBlob);
        // });
    }

    // POST请求 - 添加用户
    addUser() {
        const username = document.getElementById('username').value.trim();
        const email = document.getElementById('email').value.trim();

        // 添加客户端验证
        if (!username || username.length < 2) {
            alert('用户名至少需要2个字符');
            return;
        }

        if (!email || !(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))) {
            alert('请输入有效的邮箱地址');
            return;
        }

        const formData = new FormData();
        formData.append('action', 'addUser');
        formData.append('username', username);
        formData.append('email', email);

        fetch(this.baseUrl, {
            method: 'POST',
            // credentials: 'include', // 允许跨域请求时携带 cookie
            // headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your-token' },
            body: formData // body: JSON.stringify({ key: 'value' })
        }).then(response => {
            if (!response.ok) throw new Error('Network response was not ok' + response.statusText); // 抛出错误，以便catch处理
            return response.json()
        }).then(data => {
            if (data.success) {
                alert('用户添加成功!');
                this.loadUsers();
            } else {
                alert(data.data.message);
            }
        }).catch(error => {
            alert(`添加用户失败，请重试: ${error}`);
        });
    }

    // 文件上传
    uploadFile() {
        const fileInput = document.getElementById('fileInput');
        const file = fileInput.files[0];
        if (!file) {
            alert('请选择文件');
            return;
        }

        const formData = new FormData();
        formData.append('action', 'upload');
        formData.append('file', file);

        const xhr = new XMLHttpRequest();
        xhr.upload.addEventListener('progress', (ev) => {
            if (ev.lengthComputable) {
                const percent = (ev.loaded / ev.total) * 100;
                document.getElementById('uploadProgress').textContent = `上传进度: ${percent.toFixed(2)}%`;
            }
        });

        xhr.onload = () => {
            if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText);
                if (response.success) {
                    alert('文件上传成功！');
                    document.getElementById('uploadProgress').textContent = '';
                } else {
                    alert(response.data.message);
                }
            }
        };

        xhr.onerror = () => {
            alert('上传失败，请重试');
        };

        xhr.open('POST', this.baseUrl, true);
        xhr.send(formData);
    }

    // 显示用户列表
    displayUsers(users) {
        const userList = document.getElementById('userList');

        // 第一页时清空列表
        if (this.page === 1) userList.innerHTML = '';

        // 使用文档片段优化性能
        const fragment = document.createDocumentFragment();
        users.forEach(user => {
            const userCard = document.createElement('div');
            userCard.className = 'user-card';
            userCard.innerHTML = `
                <h3>${this.escapeHtml(user.username)}</h3>
                <p>${this.escapeHtml(user.email)}</p>
            `;
            fragment.appendChild(userCard);
        });
        userList.appendChild(fragment);

        // 如果没有更多数据，隐藏"加载更多"按钮
        if (users.length < 10) document.getElementById('loadMore').style.display = 'none';
    }

    // 添加 HTML 转义方法防止 XSS 攻击
    escapeHtml(unsafe) {
        return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
    }
}

// 初始化应用
new AjaxDemo();